#include <QgsSimulation/DrawPolylineTools.h>

using SimulationCore::QgsSimulation::DrawPolylineTools;

DrawPolylineTools::DrawPolylineTools(QgsMapCanvas* mapcanvas, const QString& action)
	:QgsMapToolEmitPoint(mapcanvas)
	, mapcanvas_(mapcanvas), action_(action)
	, is_ready_(true)
{
	this->crs_ = this->mapcanvas_->mapSettings().destinationCrs();

	this->line_rubber_band_ = new QgsRubberBand(this->mapcanvas_, QgsWkbTypes::LineGeometry);
	this->line_rubber_band_->setColor(Qt::red);
	this->line_rubber_band_->setWidth(2);

	this->point_rubber_band_ = new QgsRubberBand(mapcanvas_, QgsWkbTypes::PointGeometry);
	this->point_rubber_band_->setColor(Qt::blue);
	this->point_rubber_band_->setWidth(2);
}

DrawPolylineTools::~DrawPolylineTools()
{
	this->mapcanvas_->scene()->removeItem(this->line_rubber_band_);
	this->mapcanvas_->scene()->removeItem(this->point_rubber_band_);

	delete this->line_rubber_band_;
	delete this->point_rubber_band_;

	this->line_rubber_band_ = nullptr;
	this->point_rubber_band_ = nullptr;
}


void DrawPolylineTools::canvasPressEvent(QgsMapMouseEvent* e)
{
	if (e->button() == Qt::LeftButton) {
		//if (is_ready_)
		//{
		//	ClearGeometry();
		//	is_ready_ = false;
		//}
		this->points_.append(e->mapPoint());
		this->line_rubber_band_->addPoint(e->mapPoint());
		this->point_rubber_band_->addPoint(e->mapPoint());
	}
	else if (e->button() == Qt::RightButton) {
		//if (this->points_.size() > 1) {
		//	emit drawGeometry(this->action_, QgsWkbTypes::LineString, this->line_rubber_band_->asGeometry(), true);
		//}

		ClearGeometry();
	}
}

void DrawPolylineTools::canvasDoubleClickEvent(QgsMapMouseEvent* e)
{
	if (e->button() == Qt::LeftButton && this->points_.size() > 1) {

		emit drawGeometry(this->action_, QgsWkbTypes::LineString, this->line_rubber_band_->asGeometry(), true);
		ClearGeometry();
		//is_ready_ = true; 
	}
}

void DrawPolylineTools::deactivate()
{
	ClearGeometry();
	QgsMapToolEmitPoint::deactivate();
}

void SimulationCore::QgsSimulation::DrawPolylineTools::ClearGeometry()
{
	// clear cache data
	this->points_.clear();
	this->line_rubber_band_->reset(QgsWkbTypes::LineGeometry);
	this->point_rubber_band_->reset(QgsWkbTypes::PointGeometry);
}
